/*
 * @Author: 刘岩 15136056318@163.com
 * @Date: 2023-11-04 16:30:21
 * @LastEditors: 刘岩 15136056318@163.com
 * @LastEditTime: 2023-11-16 13:56:02
 * @FilePath: /react-template_pc/src/components/auto-fit/index.tsx
 * @Description: 大屏适配方案
 */
import type { AutoFitType, StyleEnumtype } from './data'
import { useEffect, useRef } from 'react'
let styleEnum: StyleEnumtype = {}
const AutoFit = ({
  children,
  width = 1920,
  height = 1080,
  isCover = false,
  background,
}: AutoFitType) => {
  const bigScreen = useRef<any>(null)
  const init = () => {
    const scaleWidth = window.innerWidth / width
    const scaleHeight = window.innerHeight / height
    if (isCover) {
      // 根据高度缩放比例
      styleEnum = {
        width: 'auto',
        height: height + 'px',
        transform: `scale(${scaleHeight})`,
        transformOrigin: 'top center',
      }
    } else {
      styleEnum = {
        // 根据宽高缩放比例
        width: width + 'px',
        height: height + 'px',
        transform: `scale(${scaleWidth},${scaleHeight})`,
        transformOrigin: 'top left',
      }
    }
    Object.keys(styleEnum).forEach(key => {
      bigScreen.current.style[key] = styleEnum[key]
    })
  }
  useEffect(() => {
    if (bigScreen?.current) {
      init()
      window.addEventListener('resize', () => {
        init()
      })
    }
  }, [])
  return (
    <>
      <div style={{ width: '100vw', height: '100vh', background }}>
        <div ref={bigScreen} className={`big-screen`}>
          {children}
        </div>
      </div>
    </>
  )
}
export default AutoFit
